package com.sh.caryr.erp.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    public static final String DATE_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT = "yyyy-MM-dd";
    public static final String DATE_FORMAT_MON = "yyyy-MM";
    public static final String DATE_FORMAT_MIN = "yyyy-MM-dd HH:mm";

    public static Date parseDate(String dateString, String format) {
        if (dateString == null || "".equals(dateString)) return null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            return  null;
        }
    }

    public static String formatDateTime(Date date) {
        return formatDateTime(date, DATE_FORMAT_FULL);
    }

    public static String formatDateTime(Date date, String format) {
        if (date == null) {
            return "";
        }
        if (StringUtils.isEmpty(format)) {
            format = DATE_FORMAT_FULL;
        }

        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }

    /**
     * Eg. Today is 2019-01-28 08:56:34, monthBy = -12
     *
     * @param monthBy months add
     * @return 2018-01-01 00:00:00
     */
    public static Date getStartOfMonthBy(int monthBy) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MONTH, monthBy);
        now.set(Calendar.DATE, 1);
        setStartOfDay(now);
        return now.getTime();
    }

    public static Date getStartOfDayBy(int dateBy) {
        Calendar current = Calendar.getInstance();
        current.add(Calendar.DATE, dateBy);
        setStartOfDay(current);
        return current.getTime();
    }

    /**
     * Eg. Today is 2019-01-28 08:56:34
     *
     * @return 2019-01-28 23:59:59
     */
    public static Date getEndOfToday() {
        Calendar current = Calendar.getInstance();
        setEndOfDay(current);
        return current.getTime();
    }


    /**
     * @param calendar 2019-01-28 08:56:34
     * @return 2019-01-28 00:00:00
     */
    public static void setStartOfDay(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
    }

    /**
     * @param calendar 2019-01-28 08:56:34
     * @return 2019-01-28 23:59:59
     */
    public static void setEndOfDay(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
    }

    public static void main(String args[]) {
        System.out.println(DateUtils.formatDateTime(DateUtils.getStartOfMonthBy(1), DateUtils.DATE_FORMAT_MON));
    }
}
